package com.justrun.zjutsystem.zjutsystem.service.impl;

import com.justrun.response.ResultEntity;
import com.justrun.utils.EncryptUtil;
import com.justrun.zjutsystem.zjutsystem.dtos.UserDto;
import com.justrun.zjutsystem.zjutsystem.entity.SysUser;
import com.justrun.zjutsystem.zjutsystem.entity.SysUserRole;
import com.justrun.zjutsystem.zjutsystem.mapper.SysUserMapper;
import com.justrun.zjutsystem.zjutsystem.mapper.SysUserRoleMapper;
import com.justrun.zjutsystem.zjutsystem.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author chandler
 * @since 2020-09-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity addUser(UserDto userDto) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(userDto.getUserName());
        sysUser.setPassword(EncryptUtil.sha256Encrypt(userDto.getPasssword(),
                userDto.getUserName().substring(0,6)));//用户ID的前六位字符作为加密盐值
        //插入用户表
        this.baseMapper.insert(sysUser);
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId(userDto.getRoleId());
        userRole.setUserId(sysUser.getUserId());
        //插入用户角色关联表
        sysUserRoleMapper.insert(userRole);
        return ResultEntity.ok();
    }
}
